﻿Imports SIGI.Common.BE
Imports System.IO
Imports SIGI.Common.CommonDefinitions

Public Class frmNewProperty

#Region "<< -Attributes- >>"

    Public Enum OperationResults
        Save
        Cancel
    End Enum

    Private _Properties As List(Of PropertyBE) = Nothing
    Private _TmpProperties As List(Of PropertyBE) = Nothing
    Private _DefaultInitFolder As String = Environment.SpecialFolder.Desktop
    Private _Behavior As CRUD = CRUD.Read
    Private _OwnerId As Integer = 0
    Private _AllServices As List(Of ServicesBE) = Nothing
    Private _OperationResult As OperationResults = OperationResults.Cancel
    Private _Owners As List(Of OwnerBE) = Nothing
    Private _AllowChooseOwner As Boolean = False
#End Region

#Region "<< -Properties- >>"
    Public ReadOnly Property Properties As List(Of PropertyBE)
        Get
            Return _Properties
        End Get
    End Property

    Public WriteOnly Property Behavior As CRUD
        Set(value As CRUD)
            _Behavior = value
        End Set
    End Property

    Public ReadOnly Property OperationResult As OperationResults
        Get
            Return _OperationResult
        End Get
    End Property
#End Region

#Region "<< -Events- >>"
    Private Sub frmNewProperty_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim wPropertyController As PropertyController = Nothing
        Dim wProperty As PropertyBE = Nothing
        Dim wSrv As String = String.Empty

        Try
            OpenFileDialog.InitialDirectory = _DefaultInitFolder
            'Tipos de imagenes permitidas: .jpg, .jpeg, .png, .gif, .bmp
            OpenFileDialog.Filter = "Image Files (*.bmp, *.jpg, *.jpeg, *.gif, *.png, *.bmp)|*.bmp;*.jpg; *.jpeg; *.gif; *.png; *.bmp"
            OpenFileDialog.Multiselect = False

            'Inicializo los labels de longitudes
            lblDescrLen.Text = String.Format("({0}/{1})", txtDescription.TextLength, txtDescription.MaxLength)
            lblObsLen.Text = String.Format("({0}/{1})", txtObservations.TextLength, txtObservations.MaxLength)

            'Cargo la lista de paises
            GenericMethods.GetCountries(cmbCountry)
            GenericMethods.GetCityByProvinceId(0, cmbProvince)
            GenericMethods.GetCityByProvinceId(0, cmbCity)

            'Estados de un propiedad
            LoadPropertiesStatus()

            'Tipos de propiedad
            LoadPropertiesTypes()

            'Cargo el listado de servicios
            LoadPropertyServices()

            If _AllowChooseOwner Then
                cmbOwner.Enabled = True
                lblAsteric.Visible = True
                GetOwnerList()
            End If

            If _Behavior = CRUD.Update Then
                _OwnerId = Properties(0).OwnerId
                ShowPropertyData()
                btnAddProperty.Text = "Guardar"
            End If

        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnMainImage_Click(sender As System.Object, e As System.EventArgs) Handles btnMainImage.Click
        Dim wImagePath As String
        Try
            If OpenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
                wImagePath = OpenFileDialog.FileName
                imgProperty.ImageLocation = wImagePath
            End If

        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnCancelAndQuit_Click(sender As System.Object, e As System.EventArgs) Handles btnCancelAndQuit.Click
        _OperationResult = OperationResults.Cancel
        Me.Close()
    End Sub

    Private Sub btnCancelProperty_Click(sender As System.Object, e As System.EventArgs) Handles btnCancelProperty.Click
        'Limpia todo los datos cargados
        CleanAll()
    End Sub

    Private Sub btnAddProperty_Click(sender As System.Object, e As System.EventArgs) Handles btnAddProperty.Click
        Dim wProperty As PropertyBE = Nothing
        Dim wSecondaryImages As List(Of ImagesPerPropertyBE) = Nothing
        Dim wTmp As ImagesPerPropertyBE = Nothing
        Dim wImagesLocations As List(Of String) = Nothing

        Try
            If Not ValidateRequiredFields() Then
                _MsgBox.ShowMessage("Nueva/s Propiedad/es", "Falta completar campos requeridos", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
                Return
            End If

            wImagesLocations = UC_ImageSlider1.GetImages()
            If wImagesLocations.Count > 0 Then
                wSecondaryImages = New List(Of ImagesPerPropertyBE)
                wImagesLocations.ForEach(Sub(img)
                                             wSecondaryImages.Add(New ImagesPerPropertyBE With {.Description = img})
                                         End Sub)
            End If

            wProperty = New PropertyBE
            With wProperty
                .Name = txtName.Text.Trim
                .Description = txtDescription.Text.Trim
                .Direction = txtDirection.Text.Trim
                .Country = New CountryBE With {.Id = cmbCountry.SelectedValue}
                .Province = New ProvinceBE With {.Id = cmbProvince.SelectedValue}
                .City = New CityBE With {.Id = cmbCity.SelectedValue}
                .Observations = txtObservations.Text.Trim
                .MainImage = imgProperty.ImageLocation
                .SecundaryImages = wSecondaryImages
                .Type = New PropertyTypeBE With {.Id = cmbPropertyType.SelectedValue}
                .Status = New PropertyStatusBE With {.Id = cmbStatusType.SelectedValue}
                If _AllowChooseOwner Then
                    .OwnerId = _Owners(cmbOwner.ItemIndex).Id
                Else
                    If _Behavior = CRUD.Update Then
                        .OwnerId = _OwnerId
                    End If
                End If
            End With

            'Listado de Servicios
            If wProperty.Services Is Nothing Then wProperty.Services = New List(Of ServicesBE)
            For wIdx As Integer = 0 To chkLstServices.CheckedIndices.Count - 1
                wProperty.Services.Add(_AllServices(chkLstServices.CheckedIndices(wIdx)))
            Next

            'Agrego la propiedad a la lista.
            If _Behavior = CRUD.Insert Then
                If _TmpProperties Is Nothing Then _TmpProperties = New List(Of PropertyBE)
                _TmpProperties.Add(wProperty)
            Else
                imgLstProperties.Items.Clear()
                _TmpProperties(0) = wProperty
            End If

            If String.IsNullOrEmpty(imgProperty.ImageLocation) Then
                imgLstProperties.Items.Add(txtName.Text, 0)
            Else
                ImageCollection1.AddImage(System.Drawing.Image.FromFile(imgProperty.ImageLocation))
                imgLstProperties.Items.Add(txtName.Text, ImageCollection1.Images.Count - 1)
            End If

            CleanAll()

            btnSaveAndQuit.Enabled = True
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub cmbCountry_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cmbCountry.SelectedValueChanged
        Try
            GenericMethods.GetCityByProvinceId(cmbCountry.SelectedValue, cmbProvince)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub cmbProvince_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cmbProvince.SelectedValueChanged
        Try
            GenericMethods.GetCityByProvinceId(cmbProvince.SelectedValue, cmbCity)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub txtDescription_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtDescription.TextChanged
        lblDescrLen.Text = String.Format("({0}/{1})", txtDescription.TextLength, txtDescription.MaxLength)
    End Sub

    Private Sub txtObservations_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtObservations.TextChanged
        lblObsLen.Text = String.Format("({0}/{1})", txtObservations.TextLength, txtObservations.MaxLength)
    End Sub

    Private Sub SaveAndQuit_Click(sender As System.Object, e As System.EventArgs) Handles btnSaveAndQuit.Click
        'Hago efectivo los cambios
        _Properties = _TmpProperties
        _OperationResult = OperationResults.Save
        'Las propiedades se mantienen en memoria dentro de la lista _Properties
        Me.Close()
    End Sub

    Private Sub imgLstProperties_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles imgLstProperties.KeyDown
        Dim wIdx As Integer = 0
        Dim wSelectecItems As DevExpress.XtraEditors.BaseListBoxControl.SelectedItemCollection = Nothing
        Try
            If _Behavior = CRUD.Update Then Return

            If e.KeyValue = Keys.Delete Then
                'Elimino las propiedades elegidas?
                If _MsgBox.ShowMessage("¿Quitar de la Lista?", "¿Desea quitar estas propiedades de la lista?",
                                       frmMessage.MessageType.Question_, frmMessage.MessageButtons.OkCancel) = frmMessage.MsgResult.Cancel Then
                    Return
                End If

                wSelectecItems = imgLstProperties.SelectedItems
                wIdx = wSelectecItems.Count - 1
                While (wIdx >= 0)
                    imgLstProperties.Items.Remove(wSelectecItems(wIdx))
                    wIdx -= 1
                End While

                btnSaveAndQuit.Enabled = (imgLstProperties.ItemCount > 0)
            End If
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    'Private Sub imgLstProperties_SelectedIndexChanged(sender As System.Object, e As System.EventArgs)
    '    Dim wProperty As PropertyBE = Nothing
    '    Dim wUcImage As UC_Image = Nothing

    '    Try
    '        'Verifico que este en modo "Actualización" y la lista contenga items.
    '        'If _Behavior <> CRUD.Update Or imgLstProperties.ItemCount = 0 Then Return
    '        If imgLstProperties.ItemCount = 0 Then Return
    '        'Verifico que se haya seleccionado al menos un item.
    '        If imgLstProperties.SelectedItems.Count = 0 Then Return
    '        'Muestro solo el primer item seleccionado
    '        ShowPropertyData()

    '    Catch ex As Exception
    '        _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
    '    End Try
    'End Sub
#End Region

#Region "<< -Methods- >>"

    Public Sub New(pAllowChooseOwner As Boolean, Optional pProperties As List(Of PropertyBE) = Nothing)
        Dim wImg As Image = Nothing

        InitializeComponent()
        Try
            _AllowChooseOwner = pAllowChooseOwner
            If Not pProperties Is Nothing Then
                'Cargo las propiedades ya cargadas.
                _Properties = pProperties
                'Aqui me permite hacer cambios sin alterar el estado original de la lista _Properties.
                _TmpProperties = pProperties
                'Cargo los datos que tenia de antes
                If Not _Properties Is Nothing Then
                    _Properties.ForEach(Sub(p)
                                            If String.IsNullOrEmpty(p.MainImage) Then
                                                imgLstProperties.Items.Add(p.Name, 0)
                                            Else
                                                wImg = System.Drawing.Image.FromFile(p.MainImage)
                                                ImageCollection1.AddImage(wImg)
                                                imgLstProperties.Items.Add(p.Name, ImageCollection1.Images.Count - 1)
                                            End If
                                        End Sub)
                End If
            End If

            'AddHandler imgLstProperties.SelectedIndexChanged, AddressOf imgLstProperties_SelectedIndexChanged
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try

    End Sub

    Private Sub CleanAll()
        imgProperty.ImageLocation = String.Empty
        UC_ImageSlider1.Clear()

        txtName.Text = String.Empty
        txtDirection.Text = String.Empty
        txtDescription.Text = String.Empty
        txtObservations.Text = String.Empty

        'Sin Selección
        cmbCity.SelectedValue = 0
        cmbCountry.SelectedValue = 0
        cmbProvince.SelectedValue = 0
        cmbPropertyType.SelectedValue = 0
        cmbStatusType.SelectedValue = 0

        'Deselecciono los servicios de la lista de servicios.
        For wIdx As Integer = 0 To chkLstServices.Items.Count - 1
            chkLstServices.SetItemChecked(wIdx, False)
        Next
    End Sub

    Private Function ValidateRequiredFields() As Boolean
        If _AllowChooseOwner And cmbOwner.ItemIndex = -1 Then
            cmbOwner.Focus()
            Return False
        End If

        If String.IsNullOrEmpty(txtName.Text.Trim) Then
            txtName.Focus()
            Return False
        End If

        If String.IsNullOrEmpty(txtDirection.Text.Trim) Then
            txtDirection.Focus()
            Return False
        End If

        If cmbCity.SelectedValue = 0 Then 'Sin Seleccion
            cmbCity.Focus()
            Return False
        End If

        If cmbProvince.SelectedValue = 0 Then 'Sin Seleccion
            cmbProvince.Focus()
            Return False
        End If

        If cmbCountry.SelectedValue = 0 Then 'Sin Seleccion
            cmbCountry.Focus()
            Return False
        End If

        If cmbPropertyType.SelectedValue = 0 Then 'Sin Seleccion
            cmbPropertyType.Focus()
            Return False
        End If

        If cmbStatusType.SelectedValue = 0 Then 'Sin Seleccion
            cmbStatusType.Focus()
            Return False
        End If

        Return True
    End Function

    Private Sub LoadPropertiesStatus()
        Dim wStatusList As List(Of PropertyStatusBE) = New List(Of PropertyStatusBE)
        Dim wStatus As PropertyStatusBE = Nothing

        'Sin Selección
        wStatus = New PropertyStatusBE With {.Id = 0, .Description = "Sin Selección"}
        wStatusList.Add(wStatus)

        'Para Alquilar
        wStatus = New PropertyStatusBE With {.Id = TypeOfStatePerProperty.ToRent,
                                             .Description = GenericMethods.GetEnumItemDescription(TypeOfStatePerProperty.ToRent)}

        wStatusList.Add(wStatus)

        'Para Vender
        wStatus = New PropertyStatusBE With {.Id = TypeOfStatePerProperty.ToSell,
                                             .Description = GenericMethods.GetEnumItemDescription(TypeOfStatePerProperty.ToSell)}

        wStatusList.Add(wStatus)

        'Para Vender o Alquilar
        wStatus = New PropertyStatusBE With {.Id = TypeOfStatePerProperty.ToRentOrSell,
                                             .Description = GenericMethods.GetEnumItemDescription(TypeOfStatePerProperty.ToRentOrSell)}

        wStatusList.Add(wStatus)

        If _Behavior = CRUD.Update Then
            'Alquilada
            wStatus = New PropertyStatusBE With {.Id = TypeOfStatePerProperty.Rented,
                                             .Description = GenericMethods.GetEnumItemDescription(TypeOfStatePerProperty.Rented)}

            wStatusList.Add(wStatus)

            'Vendida
            wStatus = New PropertyStatusBE With {.Id = TypeOfStatePerProperty.Selled,
                                             .Description = GenericMethods.GetEnumItemDescription(TypeOfStatePerProperty.Selled)}

            wStatusList.Add(wStatus)
        End If

        cmbStatusType.ValueMember = "Id"
        cmbStatusType.DisplayMember = "Description"
        cmbStatusType.DataSource = wStatusList
        cmbStatusType.SelectedValue = 0
    End Sub

    Private Sub LoadPropertiesTypes()
        Dim wPropertyController As PropertyController = New PropertyController
        Dim wPropertiesTypes As List(Of PropertyTypeBE) = Nothing
        Dim wPropertyType As PropertyTypeBE = New PropertyTypeBE With {.Id = 0, .Description = "Sin Selección"}

        wPropertiesTypes = wPropertyController.SearchPropertiesTypes()
        wPropertiesTypes.Insert(0, wPropertyType)

        cmbPropertyType.ValueMember = "Id"
        cmbPropertyType.DisplayMember = "Description"
        cmbPropertyType.DataSource = wPropertiesTypes
        cmbPropertyType.SelectedValue = 0
    End Sub

    Private Sub LoadPropertyServices()
        Dim wServicesController As ServicesController = New ServicesController

        _AllServices = wServicesController.Search()
        _AllServices.ForEach(Sub(s) chkLstServices.Items.Add(s.Description))
    End Sub

    Private Sub ShowPropertyData()
        Dim wProperty As PropertyBE = Nothing

        If imgLstProperties.Items.Count = 0 Or imgLstProperties.SelectedItems.Count = 0 Then Return

        'La primer propiedad seleccionada
        If imgLstProperties.Items.Count >= 1 And _Behavior <> CRUD.Update Then
            wProperty = _TmpProperties.Find(Function(p)
                                                Return p.Name = DirectCast(imgLstProperties.SelectedItems(0), DevExpress.XtraEditors.Controls.ImageListBoxItem).Value
                                            End Function)
        ElseIf imgLstProperties.Items.Count = 1 And _Behavior = CRUD.Update Then
            wProperty = _Properties(0)
        End If

        With wProperty
            If _Behavior = CRUD.Update Then .OwnerId = _OwnerId
            txtName.Text = .Name.Trim
            txtDescription.Text = .Description.Trim
            txtDirection.Text = .Direction.Trim
            txtObservations.Text = .Observations.Trim
            imgProperty.ImageLocation = IIf(Not String.IsNullOrEmpty(.MainImage), .MainImage, String.Empty)
            'Servicios
            .Services.ForEach(Sub(s)
                                  Dim wIdx As Integer = _AllServices.FindIndex(Function(srv) srv.Id = s.Id)
                                  chkLstServices.SetItemChecked(wIdx, True)
                              End Sub)
            'Imágenes Secundarias
            UC_ImageSlider1.Clear()
            If Not .SecundaryImages Is Nothing Then
                .SecundaryImages.ForEach(Sub(img) UC_ImageSlider1.AddImage(img.Description))
            End If
            cmbPropertyType.SelectedValue = .Type.Id
            cmbStatusType.SelectedValue = .Status.Id
            cmbCountry.SelectedValue = .Country.Id
            cmbProvince.SelectedValue = .Province.Id
            cmbCity.SelectedValue = .City.Id
        End With
    End Sub

    Private Sub GetOwnerList()
        Dim wOwnerController As OwnerController = New OwnerController

        _Owners = wOwnerController.Search(True)
        BindingSource1.DataSource = _Owners
        BindingSource1.ResetItem(True)
    End Sub
#End Region


End Class
